#include "CSkipButton.h"
#include <QWidget>
#include <QPainter>
#include <QFont>
#include <QBrush>
CSkipButton::CSkipButton(const QString& name, const QString& iPath, const int& index)
	:_name(name), _iPrefixPath(iPath),_drawLength(name.length()),_index(index)
	,_timer(nullptr),_timerInterval(500),_isDrawFlag(false)
	, UIElement()
{


}
CSkipButton::~CSkipButton()
{
	if (_timer) {
		delete _timer;
		_timer = nullptr;
	 }
}
void CSkipButton::setRect(const QRect& rect)
{
	if(rect.isEmpty()||!_bSelected)
	{
		if (_timer != nullptr && _timer->isActive())
		{
			_drawLength = _name.length();
			_timer->stop();
			
		}
	}
	UIElement::setRect(rect);
}
QString CSkipButton::name() const
{
	return _name;
}
void CSkipButton::setName(const QString& name)
{
	if (_name != name) {
		_name = name;
	}
	dynamic_cast<QWidget*>(_timer->parent())->update();
}


void CSkipButton::drawElement(QWidget* widget, QPainter* painter, bool bSelected, const QRect& rect)
{
	initTimer(widget);
	_isDrawFlag = true;
	_bSelected=bSelected;
	this->setRect(rect);
	drawIcon(painter);
	drawText(painter);
	_isDrawFlag = false;
}

void CSkipButton::repeat()
{
}

void CSkipButton::finish()
{

}

void CSkipButton::shortPress()
{
	if (_callBackFunc) {
		_callBackFunc();
	}
}

void CSkipButton::longPress()
{
		
}

void CSkipButton::initTimer(QWidget* widget)
{
	if (widget != nullptr&&_timer==nullptr) {
		_timer = new QTimer(widget);
		QObject::connect(_timer, &QTimer::timeout, [&]() {
				this->slotTimer();
			});
	}
}

void CSkipButton::slotTimer()
{
	if (_isDrawFlag)
	{
		return;
	}
	QWidget* widget = qobject_cast<QWidget*>(_timer->parent());
	_drawLength--;
	if (_drawLength <= 0) {
		_drawLength=_name.length();
	}
	widget->update(_rect);
}

void CSkipButton::drawIcon(QPainter* painter)
{
	QString iconPath = _iPrefixPath + (_bSelected?QString("/s/%1s.png").arg(_index):QString("/n/%1n.png").arg(_index));
	QPixmap pixmap(iconPath);
	if (pixmap.isNull()) {
		return;
	}
	_pixRect=QRect(_rect.topLeft(), pixmap.size());
	painter->drawPixmap(_pixRect, pixmap);
}

void CSkipButton::drawText(QPainter* painter)
{	if(!_bSelected)
		return;

	if (_drawLength > 0) {
		QFont font;
		font.setPixelSize(30);
		font.setFamily("Source Han Sans K");
		painter->setFont(font);
		QPen pen(QColor(255, 255, 255));
		painter->setPen(pen);
		QFontMetrics metrics(font);
		QString text(getTranslate(_name));

		int w = metrics.width(text);
		QRect textRect(_pixRect.topRight() + QPoint(8, 34), QSize(_rect.width() - _pixRect.width() - 8, metrics.height()));
		if (w > textRect.width() && _timer != nullptr) {
			if (!_timer->isActive()) {

				_timer->start(_timerInterval);
			}
		}
		painter->drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, text.right(_drawLength));
	}
}
